package wei;
import wei.Entity.Student;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "StudentServlet")
public class StudentServlet extends HttpServlet {

    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyDSTest";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        StudentRequest(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

    }
    private void StudentRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        EntityManager em = getEntityManager();

        EntityTransaction tx = em.getTransaction();

        try {


            int student_no =Integer.parseInt(request.getParameter("student_no"));
            String student_name = request.getParameter("student_name");
            String sex = request.getParameter("sex");
            int grade =Integer.parseInt(request.getParameter("grade"));
            String class_no = request.getParameter("class_no");


            Student stu = new Student(student_no, student_name, sex, grade, class_no);


            tx.begin();

            em.persist(stu);

            tx.commit();


        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {

            em.close();
        }

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println("添加学生记录成功");

        response.sendRedirect("Student.jsp");

    }

}
